Warning: This document is for the development version of AutoGIS. The main version is master.

This page was generated from source/notebooks/L5/interactive-map-folium.ipynb.
Binder badge
Binder badge CSC badge

Interactive maps on Leaflet

JavaScript (JS) is a programming language which is mostly used for adding interactive content (such a zoomamble maps!) on webpages.

Whenever you go into a website that has some kind of interactive map, it is quite probable that you are wittnessing a map that has been made with a JavaScipt library called Leaflet. Another popular JavaSCript library is called OpenLayers.

In this lesson, we will learn how to publish interactive online maps using Python and Leaflet. In spesific, we will have a look at two different libraries; Folium and mplleaflet which both allow you to create interactive maps (using the Leaflet JavaScript library) after manipulating data in Python.

Folium

Folium is a Python library that makes it possible visualize data on an interactive Leaflet map.

Resources:

Creating a simple interactive web-map

Let’s first see how we can do a simple interactive web-map without any data on it. We just visualize OpenStreetMap on a specific location of the a world.

  • First thing that we need to do is to create a Map instance. There are few parameters that we can use to adjust how in our Map instance that will affect how the background map will look like.
[1]:
import folium

# Create a Map instance
m = folium.Map(location=[60.25, 24.8],
    zoom_start=10, control_scale=True)

The first parameter location takes a pair of lat, lon values as list as an input which will determine where the map will be positioned when user opens up the map. zoom_start -parameter adjusts the default zoom-level for the map (the higher the number the closer the zoom is). control_scale defines if map should have a scalebar or not.

  • Let’s see what our map looks like:
[2]:
m
[2]:
  • We can also save the map already now
  • Let’s save the map as a html file base_map.html:
[3]:
outfp = "base_map.html"
m.save(outfp)

TASK: Navigate to the location where you saved the html file and open it in a web browser (preferably Google Chrome). Open the file also in a text editor to see the source script.

  • Let’s change the basemap style to Stamen Toner and change the location of our map slightly. The tiles -parameter is used for changing the background map provider and map style (see the documentation for all in-built options).
[4]:
# Let's change the basemap style to 'Stamen Toner'
m = folium.Map(location=[40.730610, -73.935242], tiles='Stamen Toner',
                zoom_start=12, control_scale=True, prefer_canvas=True)

m
[4]:

TASK: Modify the codeblock above and visualize a couple of different maps with different parameters (bacground maps, zoom levels etc). See documentation of class folium.folium.Map() for all avaiable options.

Adding layers to the map

Let’s first have a look how we can add a simple marker on the webmap:

[5]:
# Create a Map instance
m = folium.Map(location=[60.20, 24.96],
    zoom_start=12, control_scale=True)

# Add marker
# Run: help(folium.Icon) for more info about icons
folium.Marker(
    location=[60.20426, 24.96179],
    popup='Kumpula Campus',
    icon=folium.Icon(color='green', icon='ok-sign'),
).add_to(m)

#Show map
m
[5]:

As mentioned, Folium combines the strenghts of data manipulation in Python with the mapping capabilities of Leaflet.js. Eventually, we would like to first manipulate data using Pandas/Geopandas before creating a fancy map.

Let’s first practice by adding the address points (locations of transport stations) onto the Helsinki basemap: - read input points using Geopandas:

[6]:
import geopandas as gpd

# File path
points_fp = r"data/addresses.shp"

# Read the data
points = gpd.read_file(points_fp)

#Check input data
points.head()
[6]:
address id geometry
0 Kampinkuja 1, 00100 Helsinki, Finland 1001 POINT (24.93017 60.16837)
1 Kaivokatu 8, 00101 Helsinki, Finland 1002 POINT (24.94189 60.16987)
2 Hermanstads strandsväg 1, 00580 Helsingfors, F... 1003 POINT (24.97740 60.18736)
3 Itäväylä, 00900 Helsinki, Finland 1004 POINT (25.09196 60.21448)
4 Tyynenmerenkatu 9, 00220 Helsinki, Finland 1005 POINT (24.92148 60.15658)
[7]:
# Convert points to GeoJson
points_gjson = folium.features.GeoJson(points, name = "Public transport stations")

Now we have our population data stored as GeoJSON format which basically contains the data as text in a similar way that it would be written in the .geojson -file.

  • add the points onto the Helsinki basemap
[8]:
# Create a Map instance
m = folium.Map(location=[60.25, 24.8], tiles = 'cartodbpositron', zoom_start=10, control_scale=True)

# Add points to the map instance
points_gjson.add_to(m)

# Alternative syntax for adding points to the map instance
#m.add_child(points_gjson)

#Show map
m
[8]:

Heatmap

Folium plugins allow us to use popular plugins available in leaflet. One of these plugins is HeatMap, which creates a heatmap layer from input points.

Let’s visualize a heatmap of the public transport stations in Helsinki using the addresses input data. folium.plugins.HeatMap requires a list of points, or a numpy array as input, so we need to first manipulate the data a bit:

[9]:
# Get lat and lon coordinates
points['lon'] = points["geometry"].x
points['lat'] = points["geometry"].y

# Conver lat and lon to numpy array (old method: .as_matrix())
points_array = points[['lat', 'lon']].values

Check the output:

[10]:
print(type(points_array))
print(points_array[:5])
<class 'numpy.ndarray'>
[[60.1683731 24.9301701]
 [60.1698665 24.9418933]
 [60.1873588 24.9774004]
 [60.2144809 25.0919641]
 [60.1565781 24.9214846]]
[11]:
from folium.plugins import HeatMap

# Create a Map instance
m = folium.Map(location=[60.25, 24.8], tiles = 'stamentoner', zoom_start=10, control_scale=True)

# Add heatmap to map instance
# Available parameters: HeatMap(data, name=None, min_opacity=0.5, max_zoom=18, max_val=1.0, radius=25, blur=15, gradient=None, overlay=True, control=True, show=True)
HeatMap(points_array).add_to(m)

# Alternative syntax:
#m.add_child(HeatMap(points_array, radius=15))

# Show map
m
[11]:

Choroplet map

Next, let’s check how we can overlay a population map on top of a basemap using folium’s choropleth method. This method is able to read the geometries and attributes directly from a geodataframe. This example is modified from the Folium quicksart.

  • First read in the population grid from HSY wfs like we did in lesson 3:
[12]:
import geopandas as gpd
from pyproj import CRS
import requests
import geojson

# Specify the url for web feature service
url = 'https://kartta.hsy.fi/geoserver/wfs'

# Specify parameters (read data in json format).
# Available feature types in this particular data source: http://geo.stat.fi/geoserver/vaestoruutu/wfs?service=wfs&version=2.0.0&request=describeFeatureType
params = dict(service='WFS',
              version='2.0.0',
              request='GetFeature',
              typeName='asuminen_ja_maankaytto:Vaestotietoruudukko_2018',
              outputFormat='json')

# Fetch data from WFS using requests
r = requests.get(url, params=params)

# Create GeoDataFrame from geojson
data = gpd.GeoDataFrame.from_features(geojson.loads(r.content))

# Check the data
data.head()
[12]:
geometry index asukkaita asvaljyys ika0_9 ika10_19 ika20_29 ika30_39 ika40_49 ika50_59 ika60_69 ika70_79 ika_yli80
0 MULTIPOLYGON Z (((25476499.999 6674248.999 0.0... 3342 108 45 11 23 6 7 26 17 8 6 4
1 MULTIPOLYGON Z (((25476749.997 6674498.998 0.0... 3503 273 35 35 24 52 62 40 26 25 9 0
2 MULTIPOLYGON Z (((25476999.994 6675749.004 0.0... 3660 239 34 46 24 24 45 33 30 25 10 2
3 MULTIPOLYGON Z (((25476999.994 6675499.004 0.0... 3661 202 30 52 37 13 36 43 11 4 3 3
4 MULTIPOLYGON Z (((25476999.994 6675249.005 0.0... 3662 261 30 64 32 36 64 34 20 6 3 2
[13]:
from pyproj import CRS
# Define crs
data.crs = CRS.from_epsg(3879)
  • re-project layer into WGS 84 (epsg: 4326)
[14]:
# Re-project to WGS84
data = data.to_crs(epsg=4326)

# Check layer crs definition
print(data.crs)
{'init': 'epsg:4326', 'no_defs': True}
  • Rename columns
[15]:
# Change the name of a column
data = data.rename(columns={'asukkaita': 'pop18'})
[16]:
# Create a Geo-id which is needed by the Folium (it needs to have a unique identifier for each row)
data['geoid'] = data.index.astype(str)
[17]:
# Select only needed columns
data = data[['geoid', 'pop18', 'geometry']]

# Convert to geojson (not needed for the simple coropleth map!)
#pop_json = data.to_json()

#check data
data.head()
[17]:
geoid pop18 geometry
0 0 108 MULTIPOLYGON Z (((24.57654 60.18042 0.00000, 2...
1 1 273 MULTIPOLYGON Z (((24.58102 60.18267 0.00000, 2...
2 2 239 MULTIPOLYGON Z (((24.58538 60.19391 0.00000, 2...
3 3 202 MULTIPOLYGON Z (((24.58541 60.19166 0.00000, 2...
4 4 261 MULTIPOLYGON Z (((24.58544 60.18942 0.00000, 2...
[28]:
# Create a Map instance
m = folium.Map(location=[60.25, 24.8], tiles = 'cartodbpositron', zoom_start=10, control_scale=True)

# Plot a choropleth map
# Notice: 'geoid' column that we created earlier needs to be assigned always as the first column
folium.Choropleth(
    geo_data=data,
    name='Population in 2018',
    data=data,
    columns=['geoid', 'pop18'],
    key_on='feature.id',
    fill_color='YlOrRd',
    fill_opacity=0.7,
    line_opacity=0.2,
    line_color='white',
    line_weight=0,
    highlight=False,
    smooth_factor=1.0,
    #threshold_scale=[100, 250, 500, 1000, 2000],
    legend_name= 'Population in Helsinki').add_to(m)

#Show map
m
[28]:

Tooltips

It is possible to add different kinds of pop-up messages and tooltips to the map. Here, it would be nice to see the population of each grid cell when you hover the mouse over the map. Unfortunately this functionality is not apparently implemented implemented in the Choropleth method we used before.

Add tooltips, we can add tooltips to our map when plotting the polygons as GeoJson objects using the GeoJsonTooltip feature. (folliwing examples from here and here)

For a quick workaround, we plot the polygons on top of the coropleth map as a transparent layer, and add the tooltip to these objects. Note: this is not an optimal solution as now the polygon geometry get’s stored twice in the output!

[19]:
# Convert points to GeoJson
folium.features.GeoJson(data,  name='Labels',
               style_function=lambda x: {'color':'transparent','fillColor':'transparent','weight':0},
                tooltip=folium.features.GeoJsonTooltip(fields=['pop18'],
                                              aliases = ['Population'],
                                              labels=True,
                                              sticky=False
                                             )
                       ).add_to(m)

m
[19]:

Rember that you can also save the output as an html file:

[20]:
outfp = "results/choropleth_map.html"
m.save(outfp)

Clustered point map

Let’s visualize the address points (locations of transport stations in Helsinki) on top of the choropleth map using clustered markers.

[21]:
from folium.plugins import MarkerCluster

# Create a Clustered map where points are clustered
marker_cluster = MarkerCluster().add_to(m)
[22]:
# Create clustered points on top of the map
for idx, row in points.iterrows():
    # Get lat and lon of points
    lon = row['geometry'].x
    lat = row['geometry'].y

    # Get address informatin
    address = row['address']

    # Add marker to the marker cluster
    folium.RegularPolygonMarker(location=[lat, lon], popup=address, fill_color='#2b8cbe', number_of_sides=6, radius=8).add_to(marker_cluster)
[23]:
#Show map:
m
[23]:

Layer control

We can also add a LayerControl object on our map, which allows the user to control which map layers are visible. See the documentation for available parameters (you can e.g. change the position of the layer control icon).

[24]:
# Create a layer control object and add it to our map instance
folium.LayerControl().add_to(m)

#Show map
m
[24]:

From matplotlib to leaflet using mllpleaflet

We can also convert maptlotlib plots directly to interactive web maps using mllpleaflet.

All you need to do is to:

  1. visualize your data using matplotlib (or geodataframe.plot())
  2. convert the plot into a webmap using mplleaflet.show()

Let’s demonstrate this using the static map we plotted earler in this lesson

[25]:
import geopandas as gpd
import matplotlib.pyplot as plt
import mplleaflet
[26]:
# 1.Plot data:
points.plot()

# 2. Convert plot to a web map:
mplleaflet.show()

(the code above opens up a new tab with the visualized map)

We can also render the map insite the notebook (following this example):

[27]:
# 1. Plot data:
ax = points.plot(markersize = 50, color = "red")

# 2. Convert plot to a web map:
mplleaflet.display(fig=ax.figure, crs=points.crs)
C:\Hyapp\Anaconda3\envs\grading\lib\site-packages\IPython\core\display.py:694: UserWarning: Consider using IPython.display.IFrame instead
  warnings.warn("Consider using IPython.display.IFrame instead")
[27]:

TASK: create a map using your geopandas/matplotlib skills and convert it into a webmap using mplleaflet.show()